import {
	getCharts,
	getChartMsg,
	createNewChart,
	updateChartMsgIsRead
} from '../../common/api/middleServer/chartsApi.js'
import Vue from 'vue'
const state = {
	total: null,
	chartChange: 0,
	chartMap: {},
}

const mutations = {
	SET_CHARTLIST: (state, data) => {
		let res = data;
		state.total = res.total
		for (const key of Object.keys(res.result)) {
			Vue.set(state.chartMap, key, res.result[key])
		}
	},
	ADD_CHART: (state, chartInfo) => {
		Vue.set(state.chartMap, chartInfo.chartUserId, chartInfo)
		if(chartInfo.isNewChart===null){
			Vue.set(state.chartMap[chartInfo.chartUserId], 'isNewChart', true)
		}
		state.total += 1
	},
	SET_NOTNEWCHART: (state, chartUserId) => {
		Vue.set(state.chartMap[chartUserId], 'isNewChart', false)
	},
	UPDATE_CHART: (state, chartMsg) => {
		console.log(chartMsg)
		state.chartMap[chartMsg.receiveUserId].chartMsgVos.push(chartMsg)
		state.chartMap[chartMsg.receiveUserId].lastMsgTime=chartMsg.createTime
		state.chartMap[chartMsg.receiveUserId].notRead = 1
	},
	ADD_CHARTMSGLIST: (state, res) => {
		let chartUserId = res.chartUserId
		let chartMsgs = state.chartMap[chartUserId].chartMsgVos;
		if (!chartMsgs) {
			chartMsgs = res
		} else {
			console.log(res.records)
			chartMsgs.unshift(...res.records)
		}
		Vue.set(state.chartMap[chartUserId], 'chartMsgVos', chartMsgs)
		Vue.set(state.chartMap[chartUserId], 'msgTotalNum', res.total)
	},
	CLEAR_NOTREAD_NUM(state, chartId) {
		state.chartMap[chartId].notReadNum = 0
	},
	CLEAR_CHARTS(state) {
		state.chartMap = {}
		state.total = null
		console.log('删除会话')
	},
	CHARTMSG_CHANGE(state) {
		state.chartChange++
	},
	UPDATE_CHART_ISREAD(state, chartUserId) {
		Vue.set(state.chartMap[chartUserId], 'notRead', 0)
	}
}

const actions = {

	getUserChartList({
		commit
	}) {
		// 获取用户对话列表
		let nowNum = Object.values(state.chartMap).length;
		if (state.total == null || state.nowNum < state.total) {
			getCharts({
				startNum: nowNum,
				offset: 20
			}).then(res => {
				commit('SET_CHARTLIST', res)
			})
		}
	},

	receiveMsg({
		commit
	}, dataStr) {
		var datObj = JSON.parse(dataStr)
		console.log(datObj)
		if ('SEND_MSG_TO_USER' === datObj.event) {
			// 发送来的信息
			let chartMsg = {}
			chartMsg.chartId = datObj.chartId
			chartMsg.userId = datObj.userId
			chartMsg.receiveUserId = datObj.userId
			chartMsg.msgType = datObj.msgType
			chartMsg.msgDetail = datObj.msgDetail
			chartMsg.createTime = datObj.createTime
			chartMsg.isRead = 0
			if (!state.chartMap[datObj.userId]) {
				// 无会话时新增会话
				let chartInfo = {}
				chartInfo.chartUserId = datObj.sendUserId
				chartInfo.chartUserName = datObj.sendUserName
				chartInfo.headUserImgUrl = datObj.sendUserHeadImg
				chartInfo.notRead = 1
				let chartMsgs = []
				chartMsgs.push(chartMsg)
				chartInfo.chartMsgVos = chartMsgs;
				commit('ADD_CHART', chartInfo)
			} else {
				// 有会话更新
				commit('UPDATE_CHART', chartMsg)
				commit('CHARTMSG_CHANGE')
			}
		}
	},
	addNewChart({
		dispatch,
		commit,
		rootState
	}, chartUserId) {
		if(rootState.user.userId==chartUserId){
			uni.showToast({
				icon: 'error',
				title: '无法与自己发起会话'
			})
			return
		}
		// 查询会话列表是否已有该会话
		if (!state.chartMap[chartUserId]) {
			// 若没有该会话则调接口创建会话
			createNewChart(chartUserId).then(res=>{
				res.isNewChart=false
				commit('ADD_CHART', res)
				// 跳转会话页面
				uni.navigateTo({
					url: '/pages/charts/chart_page?chartUserId=' + chartUserId,
					fail() {
						uni.showToast({
							icon: 'error',
							title: '会话跳转失败，请向管理员反馈'
						})
					}
				})
			})
		}else{
			// 跳转会话页面
			uni.navigateTo({
				url: '/pages/charts/chart_page?chartUserId=' + chartUserId,
				fail() {
					uni.showToast({
						icon: 'error',
						title: '会话跳转失败，请向管理员反馈'
					})
				}
			})
		}
	},
	getChartMsg({
		dispatch,
		commit
	}, chartUserId) {
		if (state.chartMap == null || Object.keys(state.chartMap).length === 0) {
			// 查询
			dispatch('getUserChartList')
		}
		if (state.chartMap[chartUserId]) {
			let startN = state.chartMap[chartUserId].chartMsgVos.length
			console.log('a' + startN)
			console.log('b' + state.chartMap[chartUserId].msgTotalNum)
			if (!state.chartMap[chartUserId].msgTotalNum ||
				startN < state.chartMap[chartUserId].msgTotalNum) {
				let params = {
					chartUserId: chartUserId,
					startNum: startN,
					offset: 20
				}
				console.log(chartUserId)
				getChartMsg(params).then(res => {
					res.chartUserId = chartUserId
					commit('ADD_CHARTMSGLIST', res)
				})
			}
			return true
		}
		return false
	},
	sendMsg({
		commit
	}, chartInfo) {
		let msgData = chartInfo.msgData
		console.log(chartInfo)
		console.log(msgData)
		if (!state.chartMap[chartInfo.chartUserId]) {
			// 无会话时新增会话
			chartInfo.notRead = 0
			let chartMsgs = []
			chartMsgs.push(msgData)
			chartInfo.chartMsgVos = chartMsgs;
			commit('ADD_CHART', chartInfo)
		} else {
			// 有会话更新
			commit('UPDATE_CHART', msgData)
		}
	},
	updateMsgIsRead({
		commit
	}, chartUserId) {
		updateChartMsgIsRead({
			chartUserId: chartUserId
		}).then(res => {
			commit('UPDATE_CHART_ISREAD', chartUserId)
		})
	}
}

export default {
	namspaced: true,
	state,
	mutations,
	actions
}
